/**
 * @coderby toknan
 * @Time : 2020/7/12  16:01
 */
package com.bianys.tiwen.utils;

import com.sun.mail.util.MailSSLSocketFactory;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.security.GeneralSecurityException;
import java.util.List;
import java.util.Objects;
import java.util.Properties;
/*
        maven依赖
        <!--        邮件相关-->
        <dependency>
            <groupId>javax.activation</groupId>
            <artifactId>javax.activation-api</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>javax.mail-api</artifactId>
        </dependency>
        <dependency>
            <groupId>com.sun.activation</groupId>
            <artifactId>jakarta.activation</artifactId>
        </dependency>
        <dependency>
            <groupId>com.sun.mail</groupId>
            <artifactId>jakarta.mail</artifactId>
        </dependency>
 */

public class EmailUtils {

    public static final String EMAIL="2060695019@qq.com";
    public static final String PASSWORD="msrzebocwjolcgcc";

    //调用此方法可以完成文件的邮箱发送
    public static void sendTxtByMail(String AddresseeMail,String Theme ,String Content,String FilePath) throws MessagingException, GeneralSecurityException {
        Properties prop = new Properties();
        prop.setProperty("mail.host", "smtp.qq.com"); //// 设置QQ邮件服务器
        prop.setProperty("mail.transport.protocol", "smtp"); // 邮件发送协议
        prop.setProperty("mail.smtp.auth", "true"); // 需要验证用户名密码
        // QQ邮箱设置SSL加密
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        prop.put("mail.smtp.ssl.enable", "true");
        prop.put("mail.smtp.ssl.socketFactory", sf);
        //1、创建定义整个应用程序所需的环境信息的 Session 对象
        Session session = Session.getDefaultInstance(prop, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                //传入发件人的姓名和授权码
                return new PasswordAuthentication(EMAIL,PASSWORD);
            }
        });
        //2、通过session获取transport对象
        Transport transport = session.getTransport();
        //3、通过transport对象邮箱用户名和授权码连接邮箱服务器
        transport.connect("smtp.qq.com",EMAIL,PASSWORD);

        //4、创建邮件,传入session对
        MimeMessage mimeMessage = complexEmail(session,AddresseeMail,Theme,Content,FilePath);
        //5、发送邮件
        transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients());
        //6、关闭连接
        transport.close();
    }
    //调用此方法可以完成文本的邮箱发送
    public  static void sendMessageByMail(String AddresseeMail,String Theme ,String Content )throws MessagingException, GeneralSecurityException {
        //创建一个配置文件并保存
        Properties properties = new Properties();
        properties.setProperty("mail.host","smtp.qq.com");
        properties.setProperty("mail.transport.protocol","smtp");
        properties.setProperty("mail.smtp.auth","true");
        //QQ存在一个特性设置SSL加密
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        properties.put("mail.smtp.ssl.enable", "true");
        properties.put("mail.smtp.ssl.socketFactory", sf);
        //创建一个session对象
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(EMAIL,PASSWORD);
            }
        });
        //关闭debug模式
        session.setDebug(false);
        //获取连接对象
        Transport transport = session.getTransport();
        //连接服务器
        transport.connect("smtp.qq.com",EMAIL,PASSWORD);
        //创建邮件对象
        MimeMessage mimeMessage = new MimeMessage(session);
        //邮件发送人
        mimeMessage.setFrom(new InternetAddress(EMAIL));
        //邮件接收人
        mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress(AddresseeMail));
        //邮件标题
        mimeMessage.setSubject(Theme);
        //邮件内容
        mimeMessage.setContent(Content,"text/html;charset=UTF-8");
        //发送邮件
        transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients());
        //关闭连接
        transport.close();
    }
    //调用此方法可以批量完成文本的邮箱发送
    public  static void sendMessageByMails(List<EmailMessage> emailMessages)throws MessagingException, GeneralSecurityException {
        //创建一个配置文件并保存
        Properties properties = new Properties();
        properties.setProperty("mail.host","smtp.qq.com");
        properties.setProperty("mail.transport.protocol","smtp");
        properties.setProperty("mail.smtp.auth","true");
        //QQ存在一个特性设置SSL加密
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        properties.put("mail.smtp.ssl.enable", "true");
        properties.put("mail.smtp.ssl.socketFactory", sf);
        //创建一个session对象
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(EMAIL,PASSWORD);
            }
        });
        //关闭debug模式
        session.setDebug(false);
        //获取连接对象
        Transport transport = session.getTransport();
        //连接服务器
        transport.connect("smtp.qq.com",EMAIL,PASSWORD);
        //创建邮件对象
        MimeMessage mimeMessage = new MimeMessage(session);
        //邮件发送人
        mimeMessage.setFrom(new InternetAddress(EMAIL));
        for (EmailMessage emailMessage: emailMessages) {
            //邮件接收人
            mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress(emailMessage.addressMail));
            //邮件标题
            mimeMessage.setSubject(emailMessage.theme);
            //邮件内容
            mimeMessage.setContent(emailMessage.content,"text/html;charset=UTF-8");
            //发送邮件
            transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients());
        }
        //关闭连接
        transport.close();
    }

    //调用此方法获取复杂文本产生的mineMessage，由于发送邮件
    public static MimeMessage complexEmail(Session session,String AddresseeMail,String Theme ,String Content,String FilePath) throws MessagingException {
        //消息的固定信息
        MimeMessage mimeMessage = new MimeMessage(session);
        //发件人
        mimeMessage.setFrom(new InternetAddress(EMAIL));
        //收件人
        mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress(AddresseeMail));
        //邮件标题
        mimeMessage.setSubject(Theme);
        //邮件内容

        //准备文本
        MimeBodyPart text = new MimeBodyPart();
        text.setContent(Content,"text/html;charset=utf-8");
        //附件
        MimeBodyPart appendix = new MimeBodyPart();
        appendix.setDataHandler(new DataHandler(new FileDataSource(FilePath)));
        appendix.setFileName("BookLib.txt");
        //拼装邮件正文
        MimeMultipart mimeMultipart = new MimeMultipart();
        mimeMultipart.addBodyPart(text);
        mimeMultipart.setSubType("related");//文本内嵌成功
        //将拼装好的正文内容设置为主体
        MimeBodyPart contentText = new MimeBodyPart();
        contentText.setContent(mimeMultipart);
        //拼接附件
        MimeMultipart allFile = new MimeMultipart();
        allFile.addBodyPart(appendix);//附件
        allFile.addBodyPart(contentText);//正文
        allFile.setSubType("mixed"); //正文和附件都存在邮件中，所有类型设置为mixed
        //放到Message消息中
        mimeMessage.setContent(allFile);
        mimeMessage.saveChanges();//保存修改
        return mimeMessage;
    }

}

class EmailMessage{
    String theme;
    String content;
    String addressMail;

    public EmailMessage(String theme, String content, String addressMail) {
        this.theme = theme;
        this.content = content;
        this.addressMail = addressMail;
    }

    public EmailMessage() {

    }

    @Override
    public String toString() {
        return "EmailMessage{" +
                "theme='" + theme + '\'' +
                ", content='" + content + '\'' +
                ", addressMail='" + addressMail + '\'' +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        EmailMessage that = (EmailMessage) o;
        return Objects.equals(theme, that.theme) &&
                Objects.equals(content, that.content) &&
                Objects.equals(addressMail, that.addressMail);
    }

    @Override
    public int hashCode() {
        return Objects.hash(theme, content, addressMail);
    }

    public String getTheme() {
        return theme;
    }

    public void setTheme(String theme) {
        this.theme = theme;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getAddressMail() {
        return addressMail;
    }

    public void setAddressMail(String addressMail) {
        this.addressMail = addressMail;
    }
}